<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog v-model="props.dialogVisible" :title="type == 'ADD' ? '新增型材数据' : '编辑型材数据'" destroy-on-close @close="handleVisible('cancel')">
    <div class="import_div">
      <el-form size="small" label-width="200px" v-loading="uploadLoading">
        <template v-for="(item, index) in sectionFields" :key="index">
          <el-form-item :label="item.chinese + '(' + item.field + ')'">
            <el-input v-model="item.data" placeholder="请输入" /> 
          </el-form-item>
        </template>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer" v-loading="loading">
        <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="small" @click="handleVisible('cancel')">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {
  updateMaterialNodeData,
  addMaterialNodeData
} from '@/api/material/index.ts';
const props = defineProps(['dialogVisible', 'fields', 'type']);
const emits = defineEmits(['handleEvent']);
const tableName = ref('');
const objectId = ref('');
const loading = ref(false);
const sectionFields = ref([]);
const handleVisible = (type) => {
  emits('handleEvent', { type: 'cancel' });
};
const submitForm = () => {
  if (sectionFields.value.every((item) => item.data === '')) {
    ElMessage({ showClose: true, message: '请输入数据', type:'warning' });
    return;
  }
  const RequestApi = props.type == 'ADD'? addMaterialNodeData : updateMaterialNodeData;
  const params = {
    tableName: tableName.value,
    objectId: objectId.value,
    data: sectionFields.value
  }
  loading.value = true;
  RequestApi(params).then((res) => {
    loading.value = false;
    if (res?.code === 200) {
      ElMessage({ showClose: true, message: props.type == 'ADD' ? '型材数据新增成功' : '型材数据编辑成功', type: 'success' });
      emits('handleEvent', { type: 'success' }); 
    } 
  })
};

onMounted(() => {
  sectionFields.value = JSON.parse(JSON.stringify(props.fields));
  if (props.type == 'ADD') {
    sectionFields.value.forEach((item) => {
      item.data = '';
      item.objectId = '';
    })
    tableName.value = sectionFields.value[0].tableName;
    objectId.value = '';
  } else {
    tableName.value = sectionFields.value[0].tableName;
    objectId.value = sectionFields.value[0].objectId;
  }
})
</script>
  <style lang="scss" scoped>
.import_div {
  // display: flex;
  align-items: center;
  .error {
    margin-top: 10px;
  }
}
</style>